package com.imyuanma.qingyun.common.model.response;

import com.imyuanma.qingyun.common.config.interceptor.TraceInterceptor;
import com.imyuanma.qingyun.common.model.ECommonResultCode;
import com.imyuanma.qingyun.common.model.IResultCode;

import java.io.Serializable;

/**
 * 返回结果
 *
 * @author wangjy
 * @date 2021/12/26 23:48:05
 */
public class Result<T> implements Serializable {
    /**
     * 返回码
     */
    private int code = 0;
    /**
     * 文案
     */
    private String info = "成功";
    /**
     * 返回结果
     */
    private T data;
    /**
     * 链路id
     */
    private String traceId = TraceInterceptor.getTraceId();

    public static <T> Result<T> success() {
        return new Result<>();
    }

    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.setData(data);
        return result;
    }

    public static <T> Result<T> error(String info) {
        Result<T> result = new Result<>();
        result.setCode(ECommonResultCode.FAIL.code);
        result.setInfo(info);
        return result;
    }

    public static <T> Result<T> error(int code, String info) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setInfo(info);
        return result;
    }

    public static <T> Result<T> error(IResultCode resultCode) {
        Result<T> result = new Result<>();
        result.setCode(resultCode.code());
        result.setInfo(resultCode.info());
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("{");
        sb.append("\"code\":").append(code);
        sb.append(", \"info\":").append(info != null ? "\"" : "").append(info).append(info != null ? "\"" : "");
        sb.append(", \"data\":").append(data);
        sb.append(", \"traceId\":").append(traceId != null ? "\"" : "").append(traceId).append(traceId != null ? "\"" : "");
        sb.append('}');
        return sb.toString();
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getTraceId() {
        return traceId;
    }

    public void setTraceId(String traceId) {
        this.traceId = traceId;
    }
}
